<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import { getWeekBorrowData, getMonthBorrowData, getYearBorrowData } from '@/api/index.js';
import { ElMessage } from 'element-plus';

const props = defineProps({
  timeRange: {
    type: String,
    default: 'month'
  }
});

const chartRef = ref(null);
let chart = null;

const weekDayMap = {
  'Monday': '周一',
  'Tuesday': '周二',
  'Wednesday': '周三',
  'Thursday': '周四',
  'Friday': '周五',
  'Saturday': '周六',
  'Sunday': '周日'
};

const formatData = (rawData) => {
  if (!rawData || rawData.length === 0) return null;
  
  const result = {
    xAxis: [],
    borrow: [],
    return: []
  };

  switch (props.timeRange) {
    case 'week':
      rawData.forEach(item => {
        result.xAxis.push(weekDayMap[item.day_name] || item.day_name);
        result.borrow.push(item.borrow_count);
        result.return.push(item.return_count);
      });
      break;
    case 'month':
      rawData.forEach(item => {
        result.xAxis.push(item.day_label);
        result.borrow.push(item.borrow_count);
        result.return.push(item.return_count);
      });
      break;
    case 'year':
      rawData.forEach(item => {
        result.xAxis.push(item.month_label);
        result.borrow.push(item.borrow_count);
        result.return.push(item.return_count);
      });
      break;
  }
  
  return result;
};

const fetchData = async () => {
  try {
    let response;
    switch (props.timeRange) {
      case 'week':
        response = await getWeekBorrowData();
        break;
      case 'month':
        response = await getMonthBorrowData();
        break;
      case 'year':
        response = await getYearBorrowData();
        break;
    }
    if (response?.data) {
      const formattedData = formatData(response.data);
      if (formattedData) {
        updateChart(formattedData);
      } else {
        ElMessage.warning('暂无数据');
      }
    }
  } catch (error) {
    ElMessage.error('获取借阅数据失败');
    console.error(error);
  }
};

const updateChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['借出量', '归还量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.xAxis,
      axisLabel: {
        rotate: props.timeRange === 'month' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '借出量',
        type: 'line',
        smooth: true,
        data: data.borrow,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.3)' },
            { offset: 1, color: 'rgba(64,158,255,0.1)' }
          ])
        }
      },
      {
        name: '归还量',
        type: 'line',
        smooth: true,
        data: data.return,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103,194,58,0.3)' },
            { offset: 1, color: 'rgba(103,194,58,0.1)' }
          ])
        }
      }
    ]
  };
  
  chart?.setOption(option, true);
};

onMounted(() => {
  chart = echarts.init(chartRef.value);
  fetchData();
  
  window.addEventListener('resize', () => {
    chart?.resize();
  });
});

watch(() => props.timeRange, () => {
  fetchData();
});
</script>
